package com.gnerv.sylvanas.module.sse.logic;

import com.gnerv.sylvanas.framework.common.model.RestResult;
import com.gnerv.sylvanas.framework.common.model.sse.SseResult;
import com.gnerv.sylvanas.framework.core.BaseCurrentAccount;
import com.gnerv.sylvanas.framework.core.event.SseMessagePushEvent;
import com.gnerv.sylvanas.module.sse.model.bo.SubscribeBO;
import com.gnerv.sylvanas.module.sse.model.dto.SseMessageDTO;
import com.gnerv.sylvanas.module.sse.model.dto.SubscribeDTO;
import com.gnerv.sylvanas.module.sse.operation.SseOperationService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@Slf4j
@Service
@AllArgsConstructor
public class SseLogicService {

    private final ApplicationEventPublisher applicationEventPublisher;
    private final BaseCurrentAccount baseCurrentAccount;
    private final SseOperationService sseOperationService;

    public SseEmitter createSubscribe(SubscribeDTO subscribeDTO) {
        SseEmitter sseEmitter = sseOperationService.createSseEmitter(baseCurrentAccount.ukId());
        SubscribeBO subscribeBO = new SubscribeBO();
        subscribeBO.setClientId(baseCurrentAccount.ukId());
        subscribeBO.setTopicList(subscribeDTO.getTopicList());
        sseOperationService.createSubscribe(subscribeBO);
        return sseEmitter;
    }

    public SseEmitter updateSubscribe(SubscribeDTO subscribeDTO) {
        SseEmitter sseEmitter = sseOperationService.selectSseEmitter(baseCurrentAccount.ukId());
        SubscribeBO subscribeBO = new SubscribeBO();
        subscribeBO.setClientId(baseCurrentAccount.ukId());
        subscribeBO.setTopicList(subscribeDTO.getTopicList());
        sseOperationService.updateSubscribe(subscribeBO);
        return sseEmitter;
    }

    public SseEmitter deleteSubscribe(SubscribeDTO subscribeDTO) {
        SseEmitter sseEmitter = sseOperationService.selectSseEmitter(baseCurrentAccount.ukId());
        SubscribeBO subscribeBO = new SubscribeBO();
        subscribeBO.setClientId(baseCurrentAccount.ukId());
        subscribeBO.setTopicList(subscribeDTO.getTopicList());
        sseOperationService.deleteSubscribe(subscribeBO);
        return sseEmitter;
    }

    public RestResult<Void> sendMessage(SseMessageDTO sseMessageDTO) {
        String clientId = sseMessageDTO.getClientId();
        SseResult<?> sseResult = sseMessageDTO.getSseResult();
        applicationEventPublisher.publishEvent(new SseMessagePushEvent(clientId, sseResult));
        return RestResult.ok();
    }
}
